package com.fumasoft.dynamic.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.fumasoft.bill.server.constant.CommonConstant;
import com.fumasoft.common.dto.TokenInfoDTO;
import com.fumasoft.dynamic.ttl.CustomerTTL;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * 处理ThreadLocal 数据.
 * jingchen
 * 2025/08/30
 */
@Order(0)
@Configuration
@Slf4j
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(CommonConstant.TOKEN);
        String ip = ((HttpServletRequest) request).getHeader(CommonConstant.IP);
        String[] split = Thread.currentThread().getName().split(Constants.UNDERSCORE);
        Thread.currentThread().setName(split[0] + Constants.UNDERSCORE + UUID.randomUUID());
        try {
            TokenInfoDTO tokenInfoDTO = JSONObject.parseObject(token, TokenInfoDTO.class);
            if (tokenInfoDTO != null) {
                tokenInfoDTO.setIp(ip);
                CustomerTTL.tokenInfo.set(tokenInfoDTO);
            } else {
                String requestURI = httpServletRequest.getRequestURI();
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("filter e:", e);
            throw e;
        } finally {
            CustomerTTL.removeAll();
        }
    }
}
